/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.services;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.lifeyears.common.AssertArg;
import org.lifeyears.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Hibernate implementation of UserService
 *
 * @author Aleksander Blomskøld
 */
@Repository
public class UserServiceHibernate
    extends AbstractGenericDAOServiceHibernate<User>
    implements UserService
{
    private final Logger log = LoggerFactory.getLogger( UserServiceHibernate.class );

    @Override
    @Transactional( readOnly = true )
    public User getUserByEmailAndPassword( final String email, final String password )
    {
        AssertArg.notNull( "email", email );
        AssertArg.notNull( "password", password );
        final Criteria criteria = getSession().createCriteria( User.class );

        criteria.add( Restrictions.eq( "email", email ) );
        criteria.add( Restrictions.eq( "password", User.getHashedPassword( password ) ) );
        log.trace( "Trying to find user with email {}", email );

        final User user = (User) criteria.uniqueResult();
        log.trace( "Got user: {}", user );

        return user;
    }

    @Override
    public User getUserByEmail( final String email )
    {
        AssertArg.notNull( "email", email );

        final Criteria criteria = getSession().createCriteria( User.class );

        criteria.add( Restrictions.eq( "email", email ) );
        log.trace( "Trying to find user with email {}", email );

        final User user = (User) criteria.uniqueResult();
        log.trace( "Got user: {}", user );

        return user;

    }

}
